package com.moyun.common.aspect;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.moyun.common.annotation.OperLog;
import com.moyun.model.po.log.LogExc;
import com.moyun.service.log.LogExcService;
import com.moyun.model.po.system.SysUserEntity;
import com.moyun.service.system.SysUserService;
import com.moyun.syssecurity.util.SecurityUtil;
import com.moyun.model.po.log.SysOperLogEntity;
import com.moyun.service.log.SysOperLogService;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 切面处理类，操作日志异常日志记录处理
 *
 * @author wu
 * @date 2019/03/21
 */
@Aspect
@Component
@RequiredArgsConstructor
public class OperLogAspect {

    private final SysOperLogService los;
    private final LogExcService les;
    private final SysUserService sysUserService;


    /**
     * 设置操作日志切入点 记录操作日志 在注解的位置切入代码
     */
    @Pointcut("@annotation(com.moyun.common.annotation.OperLog)")
    public void operLogPoinCut() {
    }

    /**
     * 设置操作异常切入点记录异常日志 扫描所有controller包下操作
     */
    @Pointcut("execution(* com.moyun.*.controller..*.*(..))")
    public void operExceptionLogPoinCut() {
    }

    /**
     * @return void
     * @Author yangboxuan
     * @Description 正常返回通知，拦截用户操作日志，连接点正常执行完成后执行， 如果连接点抛出异常，则不会执行
     * 处理完请求后执行
     * @Date 2021/7/5 14:59
     * @Param [joinPoint, result]
     **/
    @AfterReturning(value = "operLogPoinCut()", returning = "result")
    public void saveOperLog(JoinPoint joinPoint, Object result) {
        // 新建系统操作日志对象
        SysOperLogEntity sysOperLog = new SysOperLogEntity();
//        sysOperLog.setOperId(IdUtil.randomUUID());
        try {
            // 获取织入点的方法,从而获取方法上的注解
            OperLog operLog = getAnnotationLog(joinPoint);
            // 提取注解的内容,进行存盘操作
            extracted(sysOperLog, operLog);
            // 将请求的相关信息保存到系统操作日志对象中
            getHttpRequestDetails(sysOperLog);
            // 保存请求参数
            Object[] args = joinPoint.getArgs();
            String argsStr = null;
            try {
                argsStr = JSONUtil.toJsonStr(args);
            } catch (Exception ignored) {
            }
            sysOperLog.setOperRequParam(argsStr);
            // 保存响应数据 (暂时注释掉,有的接口结果有 敏感数据)

            sysOperLog.setOperRespParam(JSONUtil.toJsonStr(result));
            // 获取当前登录的用户,将用户id和用户名记录下来
            extractedUserInfo(sysOperLog);
            // 获取织入点方法的类名和方法名,进行存盘操作
            String className = joinPoint.getTarget().getClass().getName();
            String methodName = joinPoint.getSignature().getName();
            sysOperLog.setOperMethod(className + "." + methodName + "()");

            sysOperLog.setOperCreateTime(new Date());
            saveLog2DB(sysOperLog);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Async
    public void saveLog2DB(SysOperLogEntity sysOperLog) {
        los.save(sysOperLog);
    }

    /**
     * 异常返回通知，用于拦截异常日志信息 连接点抛出异常后执行
     *
     * @param joinPoint 切入点
     * @param e         异常信息
     */
    @AfterThrowing(pointcut = "operExceptionLogPoinCut()", throwing = "e")
    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
        // 1. 获取当前http请求
        HttpServletRequest request = DataExtractorUtils.getRequest();
        // 2. 创建系统异常日志
        LogExc excepLog = new LogExc();
        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;
            // 保存请求参数
            Object[] args = joinPoint.getArgs();
            String argsStr = null;
            try {
                argsStr = JSONUtil.toJsonStr(args);
            } catch (Exception ignored) {
            }
            excepLog.setExcRequParam(argsStr); // 请求参数
            excepLog.setOperMethod(methodName); // 请求方法名
            excepLog.setExcName(e.getClass().getName()); // 异常名称
            excepLog.setExcMessage(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace())); // 异常信息
//            excepLog.setOperUserId(UserShiroUtil.getCurrentUserLoginName()); // 操作员ID
//            excepLog.setOperUserName(UserShiroUtil.getCurrentUserName()); // 操作员名称
//            excepLog.setOperIp(IPUtil.getRemortIP(request)); // 操作员IP
            excepLog.setOperUri(request.getRequestURI()); // 操作URI
            excepLog.setOperCreateTime(new Date()); // 发生异常时间

            les.save(excepLog);

        } catch (Exception e2) {
            e2.printStackTrace();
        }

    }


    /**
     * @return void
     * @Author yangboxuan
     * @Description 获取当前登录的用户, 将用户id和用户名记录下来
     * @Date 2021/7/3 23:32
     * @Param [sysOperLog]
     */
    private void extractedUserInfo(SysOperLogEntity sysOperLog) {
        // 1. 获取当前http请求
        HttpServletRequest request = DataExtractorUtils.getRequest();
        SysUserEntity loginUser = null;
        // 如果是登录请求,从数据库中获取用户信息。如果是登录过后的请求,则从内存中去除用户信息
        if ("/login".equals(request.getRequestURI())) {
            String username = request.getParameter("username");
            loginUser = this.sysUserService.getOne(new QueryWrapper<SysUserEntity>().eq("user_name", username));
            sysOperLog.setOperUserId(String.valueOf(loginUser.getId()));
            sysOperLog.setOperUserName(loginUser.getUsername());
        } else {
            try {
                loginUser = SecurityUtil.getLoginUser();
                sysOperLog.setOperUserId(String.valueOf(loginUser.getId()));
                sysOperLog.setOperUserName(loginUser.getUsername());
            } catch (Exception e) {
                sysOperLog.setOperUserId("接口开发测试");
                sysOperLog.setOperUserName("接口开发测试");
            }
        }
    }


    /**
     * 转换request 请求参数
     *
     * @param paramMap request获取的参数数组
     */
    public Map<String, String> converMap(Map<String, String[]> paramMap) {
        Map<String, String> rtnMap = new HashMap<String, String>();
        for (String key : paramMap.keySet()) {
            rtnMap.put(key, paramMap.get(key)[0]);
        }
        return rtnMap;
    }

    /**
     * 转换异常信息为字符串
     *
     * @param exceptionName    异常名称
     * @param exceptionMessage 异常信息
     * @param elements         堆栈信息
     */
    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuffer strbuff = new StringBuffer();
        for (StackTraceElement stet : elements) {
            strbuff.append(stet + "\n");
        }
        String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
        return message;
    }

    /**
     * @return cn.ybx.springsecuritydemo.aspecj.aop.Log
     * @Author yangboxuan
     * @Description 是否存在注解，如何存在就获取
     * @Date 2021/4/4 9:57
     * @Param [joinPoint]
     */
    private OperLog getAnnotationLog(JoinPoint joinPoint) {
        // 从切面织入点处通过反射机制获取织入点处的方法
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        // 获取切入点所在的方法
        Method method = methodSignature.getMethod();
        if (method != null) {
            return method.getAnnotation(OperLog.class);
        }
        return null;
    }

    /**
     * @return void
     * @Author yangboxuan
     * @Description 获取请求地址，请求参数
     * @Date 2021/4/7 22:05
     * @Param [joinPoint, log, operLog]
     */
    private void getHttpRequestDetails(SysOperLogEntity operLog) {
        // 获取指定请求头的参数内容
        String[] headers = {""};
        DataExtractorUtils.logHttpRequest(operLog, headers);
    }

    /**
     * @return void
     * @Author yangboxuan
     * @Description 提取注解信息，进行存盘操作
     * @Date 2021/6/30 15:31
     * @Param [sysOperLog, operLog]
     **/
    private void extracted(SysOperLogEntity sysOperLog, OperLog operLog) {
        if (operLog != null) {
            String operModul = operLog.operModul();
            BusinessType businessType = operLog.operType();
            String operDesc = operLog.operDesc();
            sysOperLog.setOperModul(operModul); // 操作模块
            sysOperLog.setOperType(businessType.name()); // 操作类型
            sysOperLog.setOperDesc(operDesc); // 操作描述
        }
    }
}
